package render.materials.textures
{
	import flash.display.BitmapData;
	import flash.display3D.textures.Texture;
	import flash.geom.Point;
	import flash.utils.ByteArray;
	
	import render.RenderManager;
	
	import utils.ApplicationDomainUtil;
	import utils.StringUtil;

	public class Texture2D
	{
		/**
		 *Texture纹理材质贴图来源类型 
		 */		
		private var _textureSourceType:int;
		/**
		 *Texture纹理材质贴图来源 
		 */		
		private var _textureSource:*;
		
		/**
		 *纹理贴图 
		 */		
		private var _texture:Texture;
		
		/**
		 *ID标识 
		 */		
		private var _id:String;
		
		public function Texture2D(id:String, textureSourceType:int, textureSource:*)
		{
			if(StringUtil.isEmpty(id))
			{
				throw new Error("创建Texture2D时，ID“"+id+"”无效");
			}
			else if(RenderManager.instance.textureLib[id]!=null)
			{
				throw new Error("创建Texture2D时，已存在相同的ID“"+id+"”");
			}
			_id=id;
			_textureSourceType=textureSourceType;
			_textureSource=textureSource;
		}

		/**
		 * 取得纹理贴图
		 */
		public function get texture():Texture
		{
			if(!_texture)
			{
				switch(_textureSourceType)
				{
					case TextureSourceType.BITMAPDATA_LINK_CLASS_NAME:
						var bitmapData:BitmapData=ApplicationDomainUtil.getDefinitionObject(_textureSource) as BitmapData;
						_texture=RenderManager.instance.createTexture(_id, TextureSourceType.BITMAPDATA, bitmapData);
						bitmapData.dispose();
						bitmapData=null;
						break;
					case TextureSourceType.BITMAPDATA:
						_texture=RenderManager.instance.createTexture(_id, _textureSourceType, _textureSource);
						break;
					case TextureSourceType.COMPRESSED_BYTEARRAY:
						_texture=RenderManager.instance.createTexture(_id, _textureSourceType, _textureSource);
						break;
					case TextureSourceType.BYTEARRAY:
						_texture=RenderManager.instance.createTexture(_id, _textureSourceType, _textureSource);
						break;
					case TextureSourceType.SIZE:
						_texture=RenderManager.instance.createTexture(_id, _textureSourceType, _textureSource);
						break;
				}
			}
			return _texture;
		}
		
		/**
		 *ID标识 
		 */
		public function get id():String
		{
			return _id;
		}
		
		/**
		 *资源清理释放
		 * 
		 */		
		public function dispose():void
		{
			switch(_textureSourceType)
			{
				case TextureSourceType.BITMAPDATA:
					var bitmapData:BitmapData=_textureSource as BitmapData;
					bitmapData.dispose();
					bitmapData=null;
					break;
				case TextureSourceType.COMPRESSED_BYTEARRAY:
				case TextureSourceType.BYTEARRAY:
					var byteArray:ByteArray=_textureSource as ByteArray;
					byteArray.clear();
					byteArray=null;
					break;
				case TextureSourceType.SIZE:
					var size:Point=_textureSource as Point;
					size=null;
					break;
			}
			_textureSource=null;
			
			if(texture)
			{
				_texture.dispose();
				_texture = null;
			}
		}
	}
}